from math import radians, sin, cos, asin, sqrt

import requests
import ujson

from config.setting import MAP_KEY
import os
import geoip2.database

from lib.redisdbs import RedisClient


def distance_calc_auto(startloc, endloc):
    startloc = startloc + ',' + endloc
    # 将十进制度数转化为弧度
    lon1, lat1, lon2, lat2 = map(radians, [float(i) for i in startloc.split(',')])
    # haversine公式
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
    c = 2 * asin(sqrt(a))
    # 地球平均半径，单位为公里
    r = 6371
    dictance = '%.3f' % (r * c)
    return dictance


# 获得地址的经纬度，即location
def get_geocode(address):
    # 参数列表key和address
    rsdb = RedisClient().conn
    r_location = rsdb.get(f'{address}_to_location')
    if r_location:
        return r_location
    if not address:
        address = '北京市'
    data = {
        'key': MAP_KEY,
        'address': address,
    }
    # 向api发送get请求
    url = 'http://restapi.amap.com/v3/geocode/geo'
    res = requests.get(url, data)
    # 将json数据加载为子典
    result = ujson.loads(res.text)
    location = result['geocodes'][0]['location']
    rsdb.set(f'{address}_to_location', location, ex=60 * 60 * 24)
    return location


def ip_to_location(ip):
    current_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    dbFile = os.path.join(current_path, "GeoLite2-City.mmdb")
    reader = geoip2.database.Reader(dbFile)
    response = reader.city(ip)
    lat = response.location.latitude
    lon = response.location.longitude
    reader.close()
    return f'{lon},{lat}'
